package org.kernely.security.persistence;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

/**
 * Roles (for example administrator, or manager...)
 */
@Entity
@Table(name="kernely_role")
public class Role implements Comparable {
	
	public final static String ROLE_ADMINISTRATOR = "Administrator";
	
	/**
	 * Role's id
	 */
	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name="role_id")
	private int id;
	
	/**
	 * Role Name
	 */
	private String name;
	
	/**
	 * Groups having this role
	 */
	@ManyToMany(
            mappedBy = "roles",
            fetch=FetchType.LAZY
        )
	private Set<Group> groups;
	
	/**
	 * Users having this role
	 */
	@ManyToMany(
            mappedBy = "roles",
            fetch=FetchType.LAZY
        )
	private Set<User> users;

	/**
	 * Constructor, with default values
	 */
	public Role(){
		this.groups = new HashSet<Group>();
		this.id = 0;
		this.name = "";
		this.users = new HashSet<User>();
	}
	
	/**
	 * @return the id
	 */
	public final int getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public final void setId(int id) {
		this.id = id;
	}

	/**
	 * @return the name
	 */
	public final String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public final void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the groups
	 */
	public final Set<Group> getGroups() {
		return groups;
	}

	/**
	 * @param groups the groups to set
	 */
	public final void setGroups(Set<Group> groups) {
		this.groups = groups;
	}

	/**
	 * @return the users
	 */
	public final Set<User> getUsers() {
		return users;
	}

	/**
	 * @param users the users to set
	 */
	public final void setUsers(Set<User> roleUsers) {
		this.users = roleUsers;
	}

	/**
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public final int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	/**
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public final boolean equals(Object obj) {
		if (this == obj){
			return true;
		}
		if (obj == null){
			return false;
		}
		if (getClass() != obj.getClass()){
			return false;
		}
		Role other = (Role) obj;
		if (id != other.id){
			return false;
		}
		if (name == null) {
			if (other.name != null){
				return false;
			}
		} else if (!name.equals(other.name)){
			return false;
		}
		return true;
	}

	/**
	 * @see java.lang.Comparable#compareTo(java.lang.Object)
	 */
	public int compareTo(Object obj) {
		if (obj != null && obj instanceof Role){
			return this.name.compareTo(((Role)obj).name);
		}	
		return 0;
	}

}
